<template>
  <div class="app-container">
    <el-container>
      <el-aside width="20%" class="aside">
        <el-form ref="form" :model="form" size="mini">
          <el-form-item label="区域名称：" prop="position">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="form" size="mini">
          <el-form-item label="区域城市名称：" prop="position">
            <el-input v-model="form.region" placeholder="请输入城市名称" disabled />
          </el-form-item>
        </el-form>
        <el-form :model="form" ref="queryForm" size="small">
          <el-form-item label="" prop="position" class="form-item">
            <div>坐标点：</div>
            <div v-for="(item, index) in form.location" :key="index" class="query-input">
              {{
                item
                  .split(",")
                  .map((coord) => parseFloat(coord).toFixed(6))
                  .join(",")
              }}
            </div>
          </el-form-item>
        </el-form>
      </el-aside>
      <el-main>
        <div style="margin-bottom: 10px; display: flex; gap: 10px;">
          <el-button size="mini" @click="drawPolygon">绘制多边形</el-button>
          <el-button size="mini" @click="drawRectangle">绘制矩形</el-button>
          <el-button size="mini" @click="drawCircle">绘制圆形</el-button>
          <el-button size="mini" type="danger" @click="clearMap">清除绘制</el-button>
        </div>
        <div id="container" ref="map" style="width: 100%; height: 70vh"></div>
      </el-main>
    </el-container>
    <el-button type="success" class="submit_btn" @click="submit">提 交 区 域</el-button>
    <el-dialog title="请选择部门" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-form-item label="部门：" prop="tap">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submits()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRegion, getArea, putRegion } from "@/api/system/area";
import { deptTreeSelect } from "@/api/system/user";
import { listPost } from "@/api/system/post";
import { createMap } from "@/utils/map.js";
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  data() {
    return {
      edit: false,
      center: [116.122046, 24.288832],
      map: null,
      polygon: null,
      polyEditor: null,
      AMap: null, // 高德地图实例
      mouseTool: null, // 鼠标绘制工具
      form: {
        name: "",
        region: "梅州市",
        location: [],
      },
      path: [],
      markers: [],
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.edit = true;
      this.fetchAreaData();
    } else {
      this.initMap();
    }
  },
  methods: {
    async fetchAreaData() {
      try {
        const response = await getArea(this.$route.query.id);
        this.form.name = response.data.name;
        const coordinates = response.data.areaLocations.map((location) => [
          parseFloat(location.longitude),
          parseFloat(location.latitude),
        ]);
        this.form.location = coordinates.map((item) => item.join(","));
        // 确保多边形闭合
        if (
          coordinates.length > 0 &&
          (coordinates[0][0] !== coordinates[coordinates.length - 1][0] ||
            coordinates[0][1] !== coordinates[coordinates.length - 1][1])
        ) {
          coordinates.push([coordinates[0][0], coordinates[0][1]]);
        }
        this.path = coordinates;
        // 确保坐标是 [lng, lat] 格式
        console.log('编辑模式加载坐标:', this.path);
        await this.initMap();
      } catch (error) {
        t;
        console.error("获取区域失败:", error);
      }
    },
    async initMap() {
      // 直接加载 AMap 和插件
      this.AMap = await AMapLoader.load({
        key: process.env.VUE_APP_webapiKey,
        version: "2.0",
        plugins: ["AMap.MouseTool"],
      });

      // 创建地图
      this.map = new this.AMap.Map(this.$refs.map, {
        center: this.path.length > 0 ? this.getPolygonCenter(this.path) : this.center,
        zoom: 14,
        mapStyle: "amap://styles/darkblue",
      });

      // 初始化鼠标绘制工具
      this.mouseTool = new this.AMap.MouseTool(this.map);

      // 如果有现有路径，绘制多边形（确保在地图加载完成后执行）
      const drawExistingPolygon = () => {
        if (this.path.length > 0) {
          console.log('绘制现有多边形，坐标:', this.path);
          this.polygon = new this.AMap.Polygon({
            path: this.path,
            strokeColor: "#FF0000",
            strokeWeight: 2,
            strokeOpacity: 0.8,
            fillOpacity: 0.3,
            fillColor: "#FF0000",
            zIndex: 50,
          });
          this.map.add(this.polygon);
          // 调整地图视野
          this.map.setFitView();
        }
      };

      // 等待地图加载完成后再绘制
      if (this.map.getContainer().offsetHeight > 0) {
        drawExistingPolygon();
      } else {
        this.map.on('complete', drawExistingPolygon);
      }

      // 监听绘制完成事件
      this.mouseTool.on("draw", (e) => {
        console.log('绘制事件触发:', e);
        this.handleDrawComplete(e.obj);
      });

      // 监听鼠标结束绘制（确保多边形能捕获到）
      this.mouseTool.on("end", (e) => {
        console.log('鼠标绘制结束:', e);
        if (e.lastPoint && this.mouseTool._drawing) {
          console.log('绘制过程中结束，检查是否是多边形');
        }
      });

      // 监听鼠标点击（备用方案）
      this.map.on("click", (e) => {
        console.log('地图点击事件:', e.lnglat);
      });
    },

    // 处理绘制完成
    handleDrawComplete(obj) {
      // 清除之前的绘制
      if (this.polygon) {
        this.map.remove(this.polygon);
      }

      this.path = [];
      console.log('绘制对象类型:', obj.constructor.name, obj);

      if (obj instanceof this.AMap.Polygon) {
        console.log('识别为多边形');
        // 多边形
        this.path = obj.getPath().map((point) => [point.lng, point.lat]);
        console.log('多边形路径:', this.path);
        // 确保闭合
        if (this.path.length > 0 && (this.path[0][0] !== this.path[this.path.length - 1][0] ||
          this.path[0][1] !== this.path[this.path.length - 1][1])) {
          this.path.push([this.path[0][0], this.path[0][1]]);
        }
      } else if (obj instanceof this.AMap.Circle) {
        // 圆形 - 转换为多边形近似
        const center = obj.getCenter();
        const radius = obj.getRadius();
        const points = 36; // 36边形近似圆形
        for (let i = 0; i < points; i++) {
          const angle = (i / points) * Math.PI * 2;
          const x = center.lng + (radius / 111000) * Math.cos(angle);
          const y = center.lat + (radius / 111000) * Math.sin(angle);
          this.path.push([x, y]);
        }
      } else if (obj instanceof this.AMap.Rectangle) {
        // 矩形
        const bounds = obj.getBounds();
        const ne = bounds.getNorthEast();
        const sw = bounds.getSouthWest();
        this.path = [
          [sw.lng, sw.lat],
          [ne.lng, sw.lat],
          [ne.lng, ne.lat],
          [sw.lng, ne.lat],
          [sw.lng, sw.lat],
        ];
      }

      // 更新当前绘制的多边形
      this.polygon = obj;

      // 更新表单数据
      this.form.location = this.path.map((item) => item.join(","));
      console.log('更新坐标点:', this.form.location);

      // 退出绘制模式
      this.mouseTool.close(false);
    },

    // 绘制多边形
    drawPolygon() {
      this.$message.info('请在地图上点击多个点绘制多边形，双击完成绘制');
      this.mouseTool.polygon();
    },
    // 绘制矩形
    drawRectangle() {
      this.$message.info('请在地图上拖拽绘制矩形');
      this.mouseTool.rectangle();
    },
    // 绘制圆形
    drawCircle() {
      this.$message.info('请在地图上拖拽绘制圆形');
      this.mouseTool.circle();
    },
    // 清除绘制
    clearMap() {
      if (this.polygon) {
        this.map.remove(this.polygon);
        this.polygon = null;
      }
      this.path = [];
      this.form.location = [];
    },

    async submit() {
      if (this.form.name === "") {
        this.$message.error(`请输入区域名称`);
        return;
      }
      if (this.path.length === 0) {
        this.$message.error(`请选择区域`);
        return;
      }
      this.getDeptTree();
      listPost().then((response) => {
        this.postList = response.rows;
      });
      this.open = true;
    },
    async submits() {
      if (!this.form.deptId) {
        this.$message.error(`请选择部门`);
        return;
      }
      if (this.edit) {
        const areaLocations = this.path.map((item) => ({
          latitude: item[1].toString(),
          longitude: item[0].toString(),
        }));
        const areaReq = {
          areaLocations: areaLocations,
          name: this.form.name,
          deptId: this.form.deptId,
        };
        areaReq.id = this.$route.query.id;
        putRegion(areaReq).then((response) => {
          this.$message.success("修改成功");
          this.$router.push({ path: "/work/region" });
        });
      } else {
        const areaLocations = this.path.map((item) => ({
          latitude: item[1].toString(),
          longitude: item[0].toString(),
        }));
        const areaReq = {
          areaLocations: areaLocations,
          name: this.form.name,
          deptId: this.form.deptId,
        };
        addRegion(areaReq).then((response) => {
          this.$message.success("提交成功");
          this.$router.push({ path: "/work/region" });
        });
      }
    },
    getPolygonCenter(paths) {
      let total = paths.length;
      let X = 0;
      let Y = 0;
      let Z = 0;
      paths.forEach((lnglat) => {
        let lng = (lnglat[0] * Math.PI) / 180;
        let lat = (lnglat[1] * Math.PI) / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;

      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      const center = [(Lng * 180) / Math.PI, (Lat * 180) / Math.PI];
      return center;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.form.deptId = data.id;
      this.form.deptName = data.label;
    },
  },
};
</script>

<style scoped>
.aside {
  background: #fff;
}

.form-item {
  height: 50vh;
  overflow-y: auto;
}

.query-input {
  margin-bottom: 10px;
}

.calcu_btn {
  margin-top: 20px;
}

.btn_box {
  position: absolute;
  right: 10px;
}

.submit_btn {
  display: flex;
  text-align: center;
  justify-content: center;
  margin: 0 auto;
  width: 20%;
}
</style>
